package com.jinzhu.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.jinzhu.pojo.AliOSSProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * 阿里云 OSS 工具类
 */

@Component
public class AliOSSUtils {

/*    private String endpoint = "https://oss-cn-beijing.aliyuncs.com";
    private String accessKeyId = "LTAI5t94ozxGmGfC6Y54jr2Y";
    private String accessKeySecret = "mac1QxeXWLl9u1x2GzqTEGmnIUu3EU";
    private String bucketName = "whz-springbootweb";*/

    //注入配置参数实体类对象
    @Autowired
    private AliOSSProperties aliOSSProperties;

    /**
     * 实现上传图片到OSS
     */
    public String upload(MultipartFile file) throws IOException {
        try (InputStream inputStream = file.getInputStream()) {
            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = UUID.randomUUID() + fileExtension;

            // 创建OSS客户端
            OSS ossClient = new OSSClientBuilder().build(
                    aliOSSProperties.getEndpoint(),
                    aliOSSProperties.getAccessKeyId(),
                    aliOSSProperties.getAccessKeySecret()
            );

            try {
                // 上传文件到OSS
                ossClient.putObject(aliOSSProperties.getBucketName(), fileName, inputStream);

                // 构建完整访问URL（关键修复点）
                return "https://" + aliOSSProperties.getBucketName() + "."
                        + aliOSSProperties.getEndpoint().replace("https://", "").replace("http://", "")
                        + "/" + fileName;
            } finally {
                ossClient.shutdown();
            }
        }
    }
}
